<template>
    <div>        
        <div id='msgBody' style="width: 80%;height: 500px;background-color: #fdffea;overflow: auto;">
            <div v-for='(item, index) in messageList' :key="index">
                <div v-if="item.from=='miss01'?true:false" >
                    <div style="text-align: center;">{{item.time}}</div>
                    <div style="float: right;">
                        <p style="color: #00aaff;">{{item.from}}</p>
                        <span >{{item.info}}</span>
                    </div>
                    <br style="clear: both;"/>    
                </div>
                <div v-else>
                    <div style="text-align: center;">{{item.time}}</div>
                    <div>
                        <p style="color: #00aaff;">{{item.from}}</p>
                        <span>{{item.info}}</span>
                    </div>            
                </div>
            </div>
        </div>
        <div id='msgFooter'>
            <el-input type="textarea" :rows="3" v-model="inputMessage" @keyup.enter.native="sendMessage()" style="outline: none;"></el-input>
            <div>
                <el-button class="sendBnt" type="primary" @click="sendMessage()" round>发送(S)</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import websdk from 'easemob-websdk'    
import WebIM from '../../utils/WebIM/WebIM'
//格式化时间
// import {renderTime} from '../../utils/WebIM/WebIM';
export default{
    name:'IMChatA',
    components:{
        
    },
    data(){        
        return{    
            user: '',  //自己应用下的用户id
            password: '123456',    //用户密码
            inputMessage:'',
            messageList:[], //消息
        }
    },
    computed: {
        username() {
            let username = localStorage.getItem('ms_username');
            return username ? username : this.user;
        },
        pwd() {
            let pwd = localStorage.getItem('ms_pwd');
            return pwd ? pwd : this.password;
        },
    },
    // mounted () { // 页面加载完调用
    //   this.$login.user = '13793105726'
    //   this.$login.pwd = '123456'
    //   this.$conn.open(this.$login)
    //   this.$conn.listen({
    //     onOpened: function ( message ) { //连接成功回调
    //       console.log('登录成功')
    //     },
    //     onTextMessage: function (message) { //收到文本消息
    //       console.log(message)
    //     }
    //   })
    // }, 
    created(){
        this.loginIM();
    },    
    methods:{
        //登陆
        loginIM(){
            var options = {
                user: this.username,
                pwd: this.pwd,
                appKey: WebIM.config.appkey,
                success: function (res) {
                    console.log(res)
                    console.log('成功')
                },
                error: function (err){
                    console.log(err)
                }
            };
            WebIM.conn.open(options);    
            this.getMessage();        
        },
        //发送消息
        sendMessage(){            
            if (!this.inputMessage || !(this.inputMessage.replace(/&nbsp;|\s/g, ''))) {
                this.$message.info('发送内容不能为空!');                
                return;
            }
            let that=this;
            let contentMsg=that.inputMessage;        
            let toID ='13793105720';   //收信息用户id
            let id = WebIM.conn.getUniqueId();                 // 生成本地消息id
            let msg = new WebIM.message('txt', id);      // 创建文本消息
            msg.set({
                msg: contentMsg,                  // 消息内容
                to: toID,                          // 接收消息对象（用户id）
                chatType: 'singleChat',                  // 设置为单聊                                     
                success: function (id, serverMsgId) {                    
                    console.log('成功发送消息');                     
                    that.sendMessageSuccessful(contentMsg,toID,'txt');                
                }, 
                fail: function(e){                            
                    console.log("发送消息失败");  
                }
            });                    
            WebIM.conn.send(msg.body);
            that.inputMessage=null;
        },
        //成功发送消息，进行消息加入到聊天信息数组中
        sendMessageSuccessful(data,toID,type){
            console.log("存储信息中》》》》》");
            let userMsg={};
            userMsg.to=toID; 
            userMsg.from=this.user;
            userMsg.info=data;
            userMsgtime=renderTime(new Date(new Date().getTime()),'yyyy-MM-dd hh:mm');
            userMsg.time=renderTime(new Date().getTime());
            userMsg.msgType=type;
            //存储信息
            this.messageList.push(userMsg);        
        },
        // 集成收到文本信息方法
        getMessage(){
            let that=this;
            WebIM.conn.listen({
                onOpened: function (message) {
                    console.log('用户已上线') // 连接成功
                },
                onTextMessage: function ( message ) {
                    console.log('收到文本信息')
                    console.log(message)
                    let date = renderTime(new Date(new Date().getTime()),'yyyy-MM-dd hh:mm');
                    let value = {}
                    // 普通文本信息
                    value = {
                        msgType: 'text',              
                        info: message.data,
                        to: message.to,
                        from: message.from,
                        time: date
                    }
                    that.messageList.push(value) // 添加到聊天信息数组中 
                }
            });            
        },                
    }
}
</script>